﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using Microsoft.Phone.Storage;
using VBFOOL.MediaPlayer.Core;
using System.Windows.Media.Animation;
namespace TestPhone
{
    public partial class PlayerPage : PhoneApplicationPage
    {
        public PlayerPage()
        {
            InitializeComponent();
        }
        private void MyPlayer_MediaFailed(object sender, ExceptionRoutedEventArgs e)
        {
            ValueLoop.Stop();
            MessageBox.Show(e.ErrorException.Message);
        }

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);
            if (e.NavigationMode == NavigationMode.New)
            {
                SystemTray.Opacity = 0.5;
                SystemTray.IsVisible = true;
                if (SystemTray.ProgressIndicator == null)
                {
                    SystemTray.ProgressIndicator = new ProgressIndicator();
                }
                SystemTray.ProgressIndicator.IsIndeterminate = true;
                SystemTray.ProgressIndicator.IsVisible = true;
                SystemTray.ProgressIndicator.Text = "努力读取中";
                System.Threading.Tasks.Task.Factory.StartNew(PlayStream);
            }
        }
        VBFOOL.MediaPlayer.Core.Interface.ISubtitleReader CurrentSubtitle = null;
        private void MyPlayer_MediaOpened(object sender, RoutedEventArgs e)
        {
            if (src != null)
            {
                if (string.IsNullOrEmpty(src.Source.Title))
                {

                }
                else
                {
                    txtTitle.Text = src.Source.Title;
                }
                var s = src.Source.Subtitles.FirstOrDefault();
                if (s != null)
                {

                    CurrentSubtitle = s;
                    int i = 0;
                    foreach (var item in s.Items)
                    {
                        MyPlayer.Markers.Add(new System.Windows.Media.TimelineMarker()
                        {
                            Time = item.TimeCode,
                            Text = i.ToString(),
                            Type = "SubtitleIndex"
                        });
                        i++;
                    }
                }
                else
                {
                    SettingPivot.Items.Remove(SubSetting);
                }


            }

            SystemTray.IsVisible = false;
            SystemTray.ProgressIndicator.IsVisible = false;

            double dt = 0;
            if (MyPlayer.NaturalDuration.HasTimeSpan)
            {
                dt = MyPlayer.NaturalDuration.TimeSpan.TotalSeconds;
            }
            SeekProgress.Maximum = dt;
            ValueLoop.Interval = TimeSpan.FromSeconds(0.1);
            ValueLoop.Tick += ValueLoop_Tick;
            ValueLoop.Start();
        }
        bool IsSeek = true;
        void ValueLoop_Tick(object sender, EventArgs e)
        {
            IsSeek = false;
            SeekProgress.Value = MyPlayer.Position.TotalSeconds;
            txtTimePosition.Text = string.Format(@"{0:hh\:mm\:ss} / {1:hh\:mm\:ss}", MyPlayer.Position, MyPlayer.NaturalDuration.TimeSpan);
            //txtMem.Text = string.Format("Memory:{0:N}", Windows.Phone.System.Memory.MemoryManager.ProcessCommittedBytes);
        }

        private void MyPlayer_MediaEnded(object sender, RoutedEventArgs e)
        {
            ValueLoop.Stop();
            App.PlayingStream.Close();
            if (NavigationService.CanGoBack)
            {
                NavigationService.GoBack();
            }
        }

        void PlayStream()
        {
            var ms = App.PlayingStream;
            ms.Position = 0;
            LibEBML.Common.Matroska mat = new LibEBML.Common.Matroska(new LibEBML.Common.EBMLDocument(ms));
            VBFOOL.MediaPlayer.MKV.MKVFileSource fs = new VBFOOL.MediaPlayer.MKV.MKVFileSource(mat);
            VBFOOL.MediaPlayer.Codecs.H264Codec c1 = new VBFOOL.MediaPlayer.Codecs.H264Codec();
            VBFOOL.MediaPlayer.Codecs.AACCodec aac = new VBFOOL.MediaPlayer.Codecs.AACCodec();
            fs.Codecs.Add(c1);
            fs.Codecs.Add(aac);
            fs.Codecs.Add(new VBFOOL.MediaPlayer.Codecs.FlacCodec());
            src = new OpenMediaStreamSource(fs);
            //MyMediaStreamSource src = new MyMediaStreamSource(ms);
            Dispatcher.BeginInvoke(() =>
            {
                MyPlayer.SetSource(src);
                MyPlayer.Play();
            });
        }
        OpenMediaStreamSource src = null;
        System.Windows.Threading.DispatcherTimer ValueLoop = new System.Windows.Threading.DispatcherTimer();
        private void SeekProgress_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
        {
            if (IsSeek)
            {
                var m = e.NewValue;
                MyPlayer.Position = TimeSpan.FromSeconds(m);
            }
            IsSeek = true;

        }


        private void btnPlay_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            switch (MyPlayer.CurrentState)
            {
                case System.Windows.Media.MediaElementState.AcquiringLicense:
                    break;
                case System.Windows.Media.MediaElementState.Buffering:
                    break;
                case System.Windows.Media.MediaElementState.Closed:
                    break;
                case System.Windows.Media.MediaElementState.Individualizing:
                    break;
                case System.Windows.Media.MediaElementState.Opening:
                    break;
                case System.Windows.Media.MediaElementState.Paused:
                    MyPlayer.Play();
                    break;
                case System.Windows.Media.MediaElementState.Playing:
                    if (MyPlayer.CanPause)
                    {
                        MyPlayer.Pause();
                    }
                    break;
                case System.Windows.Media.MediaElementState.Stopped:
                    MyPlayer.Play();
                    break;
                default:
                    break;
            }
        }

        private void Rectangle_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            if (ControlGrid.Visibility == System.Windows.Visibility.Visible)
            {
                ControlGrid.Visibility = System.Windows.Visibility.Collapsed;
            }
            else
            {
                ControlGrid.Visibility = System.Windows.Visibility.Visible;
            }
            HeadGrid.Visibility = ControlGrid.Visibility;
        }

        private void LayoutRoot_Loaded(object sender, RoutedEventArgs e)
        {
        }

        private void MyPlayer_MarkerReached(object sender, System.Windows.Media.TimelineMarkerRoutedEventArgs e)
        {
            if (e.Marker.Type == "SubtitleIndex")
            {
                //txtSubtitle.Visibility = System.Windows.Visibility.Visible;
                var str = e.Marker.Text;
                int i = int.Parse(str);
                var item = CurrentSubtitle[i];
                txtSubtitle.Text = item.Text;
                txtSubtitleBack.Text = item.Text;
                Storyboard sb = new Storyboard();
                var kf = new ObjectAnimationUsingKeyFrames();
                kf.KeyFrames.Add(new DiscreteObjectKeyFrame() { Value = System.Windows.Visibility.Visible, KeyTime = KeyTime.FromTimeSpan(TimeSpan.Zero) });
                kf.KeyFrames.Add(new DiscreteObjectKeyFrame() { Value = System.Windows.Visibility.Collapsed, KeyTime = KeyTime.FromTimeSpan(item.Duration) });
                Storyboard.SetTarget(kf, txtSubtitleBack);
                Storyboard.SetTargetProperty(kf, new PropertyPath("TextBlock.Visibility"));
                sb.Children.Add(kf);
                kf = new ObjectAnimationUsingKeyFrames();
                kf.KeyFrames.Add(new DiscreteObjectKeyFrame() { Value = System.Windows.Visibility.Visible, KeyTime = KeyTime.FromTimeSpan(TimeSpan.Zero) });
                kf.KeyFrames.Add(new DiscreteObjectKeyFrame() { Value = System.Windows.Visibility.Collapsed, KeyTime = KeyTime.FromTimeSpan(item.Duration) });
                Storyboard.SetTarget(kf, txtSubtitle);
                Storyboard.SetTargetProperty(kf, new PropertyPath("TextBlock.Visibility"));
                sb.Children.Add(kf);
                sb.Duration = new Duration(item.Duration);
                sb.AutoReverse = false;
                sb.FillBehavior = FillBehavior.HoldEnd;
                sb.Begin();
            }
        }

        private void Menu_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            switch (this.SupportedOrientations)
            {
                case SupportedPageOrientation.Landscape:
                    SettingPivot.Height = this.ActualWidth * 0.5;
                    this.SupportedOrientations = SupportedPageOrientation.Portrait;
                    SettingGrid.Visibility = System.Windows.Visibility.Visible;
                    break;
                case SupportedPageOrientation.Portrait:
                    this.SupportedOrientations = SupportedPageOrientation.Landscape;
                    SettingGrid.Visibility = System.Windows.Visibility.Collapsed;
                    break;
                case SupportedPageOrientation.PortraitOrLandscape:
                    break;
                default:
                    break;
            }
        }
    }
}